package connection;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import server.ClientThread;
import server.UsersController;

import comum.Client;
import comum.ServerInfo;


/**
 * @author Guilherme
 *
 * Classe responsavel por receber os pedidos de conexoes dos clientes
 * Ela quem inicializa a thread do cliente e espera os novos
 */
public class ReceberConexoes {
	
	/**
	 * Recebe as conexoes dos clientes, processa e envia resposta
	 */
	public ReceberConexoes() {
		System.out.println("Aguardando conexoes...");
		Socket pacote=null;
		String ip=null, text=null;
		try
		{
			ServerSocket servidor = new ServerSocket(8000);
			while(true) {
				// Escutando chamadas de clientes
				pacote = servidor.accept();
				ip = pacote.getInetAddress().getHostAddress();
				//interpretando mensagem
				BufferedReader reader = new BufferedReader(new InputStreamReader(pacote.getInputStream()));
				text = reader.readLine();
				System.out.println(text);
				Client client = this.startUser(ip, text);
				
				PrintWriter out = new PrintWriter(pacote.getOutputStream(), true);
				out.println(getLoginMessage(client));
				System.out.println("Servidor enviou a msg");
				out.close();
			}
		}
		catch(Exception e) {
				System.out.println("Error: " + e);
		}
	}
	
	
	/**
	 * Inicia usuario e abre sua thread
	 * @param ip
	 * @param message
	 * @return Client
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	protected Client startUser(String ip, String message) throws ClassNotFoundException, IOException {
		System.out.println("Iniciando usuario. End: "+ip+":"+message);
		
		Client client = new Client(ip, Integer.parseInt(message));
		client.setIpServer(ServerInfo.getServerIp());
		client.setPortServer(ServerInfo.getProximaPorta());
		UsersController.addUser(client);
		
		new ClientThread(client).start();
		
		return client;
	}
	
	/**
	 * Monta request de login
	 * @param client
	 * @return
	 */
	protected String getLoginMessage (Client client){
		String Mensagem = "serverip->"+client.getIp()+"\n";
		Mensagem += "serverport->"+client.getPort()+"\n";
		Mensagem += "clientip->"+client.getIpServer()+"\n";
		Mensagem += "clientport->"+client.getPortServer()+"\n";
		return Mensagem;
	}
	
}
